﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.XPath;

namespace DBLGen.UI.Design.Query.DBAdapter
{
	public class QueryRow
	{
		public int Order { get; set; }
		public string FieldName { get; set; }
		public string Conjunction { get; set; }
		public string Operation { get; set; }
		public string ParameterName { get; set; }
		public string DefaultValue { get; set; }
		public Operand Operand
		{
			get {
				if (!string.IsNullOrEmpty(this.Operation))
				{
					return (Operand)Enum.Parse(typeof(Operand), this.Operation);
				}
				throw new ArgumentNullException("You need first to fill Operation property");
			}
		}
		
		public QueryRow() { }
		public QueryRow(int order, string fieldName, string operation, string conjunction, string parameterName, string defaultValue) 
		{
			this.Order = order;
			this.FieldName = fieldName;
			this.Operation = operation;
			this.Conjunction = conjunction;
			this.ParameterName = parameterName;
			this.DefaultValue = defaultValue;
		}

		#region Xml Persistence
		internal void SaveXml(XmlWriter writer)
		{
			writer.WriteStartElement("CustomAttributeQueryType");
			writer.WriteAttributeString("order", this.Order.ToString());
			writer.WriteAttributeString("fieldName", this.FieldName.ToString());
			writer.WriteAttributeString("conjunction", this.Conjunction.ToString());
			writer.WriteAttributeString("parameterName", this.ParameterName.ToString());
			writer.WriteAttributeString("defaultValue", this.DefaultValue.ToString());
			writer.WriteAttributeString("operation", this.Operation.ToString());
			writer.WriteEndElement();
		}

		internal static QueryRow LoadFromXml(XPathNavigator navigator)
		{
			string orderId = navigator.GetAttribute("order", navigator.NamespaceURI);
			string fieldName = navigator.GetAttribute("fieldName", navigator.NamespaceURI);
			string conjunction = navigator.GetAttribute("conjunction", navigator.NamespaceURI);
			string parameterName = navigator.GetAttribute("parameterName", navigator.NamespaceURI);
			string defaultValue = navigator.GetAttribute("defaultValue", navigator.NamespaceURI);
			string operation = navigator.GetAttribute("operation", navigator.NamespaceURI);

			int sortOrder = 0;
			int.TryParse(orderId, out sortOrder);

			return new QueryRow(sortOrder, fieldName, operation, conjunction, parameterName, defaultValue);
		}
		#endregion Xml Persistence

	}
}
